package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.FlightAirport;
import cn.wolfcode.luowowo.article.domain.FlightInfo;
import cn.wolfcode.luowowo.article.domain.FlightOrder;
import cn.wolfcode.luowowo.article.mapper.FlightAirportMapper;
import cn.wolfcode.luowowo.article.mapper.FlightInfoMapper;
import cn.wolfcode.luowowo.article.mapper.FlightOrderMapper;
import cn.wolfcode.luowowo.article.query.FlightInfoQuery;
import cn.wolfcode.luowowo.article.service.IFlightService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FlightServiceImpl implements IFlightService {

    @Autowired
    private FlightAirportMapper airportMapper;

    @Autowired
    private FlightInfoMapper infoMapper;

    @Autowired
    private FlightOrderMapper orderMapper;

    public Map queryByInitial(String beginInitial, String endInitial) {
        Map<String, ArrayList<FlightAirport>> map = new HashMap<>();

        List<FlightAirport> airports = airportMapper.selectByInitial(beginInitial, endInitial);
        for (FlightAirport airport : airports) {
            String key = airport.getInitial();
            ArrayList<FlightAirport> list = new ArrayList<>();
            if (map.containsKey(key)){
                list = map.get(key);
                for (FlightAirport ele : list) {
                    if (ele.getDest().getName().equals(airport.getDest().getName())){
                        airport = null;
                    }
                }
            }
            if (airport!=null){
                list.add(airport);
                map.put(key, list);
            }
        }
        return map;
    }

    public List<FlightAirport> queryHots() {
        List<FlightAirport> flightAirports = airportMapper.selectHots();
        return flightAirports;
    }

    public List<FlightInfo> queryInfo(FlightInfoQuery qo) {
        return infoMapper.query(qo);
    }

    public FlightInfo getInfoById(Long id) {
        return infoMapper.selectByPrimaryKey(id);
    }

    public void saveOrder(FlightOrder order) throws LogicException {
        AssertUtil.hasLength(order.getPassenger(), "乘机人姓名不能为空");
        AssertUtil.hasLength(order.getIdcardNo(), "乘机人证件不能为空");
        AssertUtil.hasLength(order.getLinkman(), "联系人姓名不能为空");
        AssertUtil.hasLength(order.getLinktel(), "联系人电话不能为空");
        orderMapper.insert(order);
    }

    public List<FlightOrder> queryByUser(Long uid) {
        return orderMapper.selectByUserId(uid);
    }
}
